//
//  ViewController.m
//  QZTabBarContentView
//
//  Created by admin on 2017/8/10.
//  Copyright © 2017年 QZ. All rights reserved.
//


#import "HomeViewController.h"
#import "QZTabBarContentView.h"
#import "Masonry/Masonry.h"
#import "LCHomeTableViewController.h"
#import "HomeViewController+LCTopTitleImageBar.h"

//视频
#import "LCBeautifulEssayController.h"
#import "LCRecommendCollection.h"
#import "UIViewController+LCHidden.h"

CFAbsoluteTime StartTime;
@interface HomeViewController ()
<QZTabBarContentViewDataSource,QZTabBarContentViewDelegate>

@property (weak, nonatomic) IBOutlet QZTabBarContentView *tabBarContentView;
@property (strong, nonatomic) LCHomeTableViewController *homeTableViewController;
@property (strong, nonatomic) LSZNewTabbarAudioVC * NewTabbarAudioVC;//音频
@property (nonatomic,strong) LCRecommendCollection *recommendCollectionViewController;

@property (nonatomic,strong) NSArray *array;;//


@end

@implementation HomeViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    _topTitleImageBar.isPushSerach = YES;
    [LCFloatingWindow sharedInstance].hidden = YES;
    NSString * homePage = [[NSUserDefaults standardUserDefaults] objectForKey:@"homePage"];
    if ([homePage isEqualToString:@"yes"]) {
        return;
    }
    if (![[_UserM usercode] isEqualToString:@""]) {
        //获取用户的信息
        [LSZRequestResolutionDic initWithGetUserInformation:^(BOOL isOK, NSString * str, LSZPersonalInformationManager * manager) {
            if(isOK == YES ){
                NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
                [userDefaults setObject:@"yes" forKey:@"homePage"];
            }
        }];
    }

}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = RGBColor(228, 83, 77);
    [self setupTitleImageView];
    StartTime = CFAbsoluteTimeGetCurrent();
    self.tabBarContentView.tabBarTitleStyle = 1;
    self.tabBarContentView.dataSource = self;
    self.tabBarContentView.delegate = self;
    [self setupTabBar];//解决自动的向下偏移64像素
    _array = @[@"推荐",@"音频",@"视频"];

    [self.tabBarContentView reloadData];
    [self.tabBarContentView.lingNumberButton addTarget:self action:@selector(clickPushSearchView) forControlEvents:(UIControlEventTouchUpInside)];
    [self.tabBarContentView.findButBG addTarget:self action:@selector(clickPushSearchView) forControlEvents:(UIControlEventTouchUpInside)];

    [self loadShopData];

    [self performSelector:@selector(setupShop) withObject:nil/*可传任意类型参数*/ afterDelay:0.4];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reachabilityChanged:)
                                                 name:kReachabilityChangedNotification
                                               object:nil];
    NSString *url = [NSString stringWithFormat:@"%@?%@",shoopLogin,[UserPageManager getUrlStrMove]];
    Reachability *reach = [Reachability reachabilityWithHostName:url];
    [reach startNotifier];
}
- (void)reachabilityChanged:(NSNotification *)notification{
    Reachability *reach = [notification object];
    if([reach isKindOfClass:[Reachability class]]){
        NetworkStatus status = [reach currentReachabilityStatus];
        if (status == NotReachable){
            return;
        }else {
            [self loadShopData];
        }
    }
}

- (void)loadShopData {
    NSString *uid = [NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]];
    if([uid isEqualToString:@""]){
        return;
    }
    if([_UserM.usercode isEqualToString:@""]){
        return;
    }
    #pragma mark -  加载主内商城网页  -
    NSString *url = [NSString stringWithFormat:@"%@?%@",shoopLogin,[UserPageManager getUrlStrMove]];
    Reachability *reach = [Reachability reachabilityWithHostName:url];
    if ([reach currentReachabilityStatus] == NotReachable){
        return;
    }
    [PAWebView shareInstance].link = url;
    [[PAWebView shareInstance] loadRequestURL:[NSURL URLWithString:url]];
}

- (void)setupShop {
    [PAWebView shareInstance].view.hidden = YES;
    [[[UIApplication sharedApplication].delegate window] addSubview:[PAWebView shareInstance].view];
    [PAWebView shareInstance].view.frame = CGRectMake(0, NAVIGATION_BAR_HEIGHT, ScreenWidth, ScreenHeight-NAVIGATION_BAR_HEIGHT-HOME_INDICATOR_HEIGHT+(iPhoneX ? 10.f : 0.f));
    [PAWebView shareInstance].webView.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight-NAVIGATION_BAR_HEIGHT-HOME_INDICATOR_HEIGHT+(iPhoneX ? 10.f : 0.f));
    CGRect barFrame = CGRectMake(0,0, ScreenHeight, 2);
    [PAWebView shareInstance].wkProgressView.frame = barFrame;
}


///解决自动的向下偏移64像素
- (void)setupTabBar {
    // iOS7.0的特性 : 当滚动视图及其子类(UIScrollView/UIWebView/UITablewView/UICollectionView/UITexeView...)在自动布局时,遇到导航,里面的内容会自动的向下偏移64像素.
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.tabBarController.tabBar.translucent = NO;//设置为不半透明也可以解决灰色的tabBar问题
//    self.tabBarController.tabBar.backgroundImage = [self imageWithColor:[UIColor whiteColor]];
//    self.tabBarController.tabBar.shadowImage = [UIImage new];
}
- (UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0.0f,0.0f, 1.0f,1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context =UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image =UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
#pragma mark - QZTabBarContentViewDelegate -

-(UIColor *)highlightColorForTabBarItemInTabBarContentView:(QZTabBarContentView *)tabBarContentView{
    return RGBColor(235, 82, 74);
}
-(CGFloat)heightForTabBarInTabBarContentView:(QZTabBarContentView *)tabBarContentView{
    return 44;
}
-(UIColor *)colorForTabBarItemTextInTabBarContentView:(QZTabBarContentView *)tabBarContentView{
    return RGBColor(140, 140, 140);
}

#pragma mark - QZTabBarContentViewDataSource -
/**
 放回当前控件需要多少个选项
 @param tabBarContentView 当前控件
 @return 返回选项个数
 */
- (NSInteger)numberOfItemsInTabBarContentView:(QZTabBarContentView *)tabBarContentView {
//    return _count;
    return _array.count;
}
/**
 提供选项的标题
 @param tabBarContentView 当前控件
 @param index 标题索引
 @return 返回标题内容
 */
- (NSString *)tabBarContentView:(QZTabBarContentView *)tabBarContentView titleForItemAtIndex:(NSInteger)index {
    return [NSString stringWithFormat:@"%@",_array[index]];
    //return [NSString stringWithFormat:@"item %zd",index];
}
/**
 提供内容视图
 @param tabBarContentView 当前控件
 @param index 标题索引
 @return 内容视图
 */
- (UIView *)tabBarContentView:(QZTabBarContentView *)tabBarContentView contentViewAtIndex:(NSInteger)index {
    //圣经
    if (index == 0) {
        self.homeTableViewController = [[LCHomeTableViewController alloc] init];
        [self addChildViewController:self.homeTableViewController];
        __weak typeof(self) weakSelf = self;
        self.homeTableViewController.pushVCBlock = ^(NSArray *arr) {
            NSString *pushStr = arr[0];
            NSString *pushType;
            if (arr.count == 2) {
                 pushType = arr[1];
            }
            if (arr.count == 2) {//轮播图跳转
// pushStr = @"http://fuyin.app.inping.com/shuang11/index.php?usercode=&type=1";//双十一csURL
// pushStr = @"http://buy.9ku.com/wap/goods/goodsdetail?id=63&usercode=";//电商csURL
                NSLog(@"pushStr = %@", pushStr);

                if ([pushType isEqualToString:@"1"]) { ////1.捐赠
                    pushStr = [pushStr stringByReplacingOccurrencesOfString:@"usercode=" withString:[NSString stringWithFormat:@"usercode=%@",[_UserM usercode]]];

                    if([[_UserM usercode] isEqualToString:@""]){
                        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"AccLogin" bundle:nil];
                        UIViewController *controller = [sb instantiateInitialViewController];
                        [weakSelf.navigationController pushViewController:controller animated:YES];
                    }else{
                        LCVideoHtmlDetailsController *viewController = [[LCVideoHtmlDetailsController alloc] init];
                        viewController.link = pushStr;
                        [weakSelf.navigationController pushViewController:viewController animated:YES];
                    }
                }else if ([pushType isEqualToString:@"2"]) { //2.电商
                    
                    if([[_UserM usercode] isEqualToString:@""]){
                        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"AccLogin" bundle:nil];
                        UIViewController *controller = [sb instantiateInitialViewController];
                        [weakSelf.navigationController pushViewController:controller animated:YES];
                    }else{
                        LSZFindOutMoreVC *viewController = [[LSZFindOutMoreVC alloc] init];
                        viewController.type = @"2";
                        viewController.link = pushStr;
                        [weakSelf.navigationController pushViewController:viewController animated:YES];
                    }
                }else if ([pushType isEqualToString:@"0"]){//0. 文章视频
                    LSZPromotionalGraphicDetailsVC *vc = [[LSZPromotionalGraphicDetailsVC alloc] init];
                    vc.url = pushStr;
                    vc.modalPresentationStyle = UIModalPresentationOverFullScreen;
                    [weakSelf presentViewController:vc animated:YES completion:nil];
                }
                return ;
            }
           else if ([pushStr hasPrefix:@"http://"]) {
                NSLog(@"pushStr = %@", pushStr);
                LCWenHTMLViewController *viewController = [[LCWenHTMLViewController alloc] init];
                viewController.link = pushStr;
                [weakSelf.navigationController pushViewController:viewController animated:YES];
            }
           else if ([pushStr isEqualToString:@"1"]) {
                LSZPraisePoetryAndSermonsVC *viewController = [[LSZPraisePoetryAndSermonsVC alloc] init];
                viewController.strTitile = @"赞美诗歌";
                [weakSelf.navigationController pushViewController:viewController animated:YES];
            }
            //了解基督
           else if ([pushStr isEqualToString:@"4"]){
               LSZKnowChristVC * vc = [[LSZKnowChristVC alloc] init];
               vc.act = 0;
               vc.id_id = @"";
               [weakSelf.navigationController pushViewController:vc animated:YES];
           }
           else if ([pushStr isEqualToString:@"5"]){
                LSZPraisePoetryAndSermonsVC *viewController = [[LSZPraisePoetryAndSermonsVC alloc] init];
                viewController.strTitile = @"牧师讲道";
                [weakSelf.navigationController pushViewController:viewController animated:YES];
                
            }
            else if([pushStr isEqualToString:@"7"]){
                if([[_UserM usercode] isEqualToString:@""]){
                    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"AccLogin" bundle:nil];
                    UIViewController *controller = [sb instantiateInitialViewController];
                    [weakSelf.navigationController pushViewController:controller animated:YES];
                }else{
                    LSZFindOutMoreVC * vc = [[LSZFindOutMoreVC alloc]init];
                    [weakSelf.navigationController pushViewController:vc animated:YES];
                }
            }
            else {
                NSString *clzName = pushStr;
                Class clz = NSClassFromString(clzName);//将字符串转化成class
                UIViewController *viewController = [[clz alloc] init];
                [weakSelf.navigationController pushViewController:viewController animated:YES];
            }
        };
        return self.homeTableViewController.view;
    }
    //音频
    if (index == 1) {
        LSZNewTabbarAudioVC * VC = [[LSZNewTabbarAudioVC alloc]init];
        //一定要加下面这句  不然不能push
        [self addChildViewController:VC];
        return VC.view;
    }
    //视频
   if(index == 2)
   {
       LCRecommendCollection *recommendCollectionViewController = [[LCRecommendCollection alloc] init];
       _recommendCollectionViewController = recommendCollectionViewController;
       [self addChildViewController:recommendCollectionViewController];
       return recommendCollectionViewController.view;
    }
    //商城
    UILabel *label = [UILabel new];
    label.text = [NSString stringWithFormat:@"这个地方用H5界面 %@",_array[index]];
    label.textAlignment = NSTextAlignmentCenter;
    return label;
}
#pragma mark - QZTabBarContentViewDelegate -
/**
 返回一个当前选项选中的视图
 @param tabBarContentView 当前控件
 @return 选中的视图
 */
- (UIView *)highlightViewForTabBarItemInTabBarContentView:(QZTabBarContentView *)tabBarContentView {
    UIView *view = [UIView new];
    
    UIView *line = [UIView new];
    line.backgroundColor = redUIColor;//[UIColor whiteColor];
//    // 设置圆角大小
//    line.radius = 1;
    [view addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(view).offset(-5);
        make.centerX.equalTo(view);
        make.width.mas_equalTo(18);
        make.height.mas_equalTo(2);
    }];
    
    return view;
}
/**
 当选中状态发生改变时回调
 
 @param tabBarContentView 当前控件
 @param index 选项下标
 */
- (void)tabBarContentView:(QZTabBarContentView *)tabBarContentView didSelectItemAtIndex:(NSInteger)index {
    NSLog(@"index:%zd",index);
    if (index == 1) {
     }
    if (index == 2) {
    }
}


@end
